<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblog/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/myblog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/myblog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/myblog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16.png?v=5.1.4">


  <link rel="mask-icon" href="/myblog/images/safari-pinned-tab.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,stream,转载,">










<meta name="description" content="作者：Howie_Y   主页：www.jianshu.com/u/79638e5f0743  Java 8 发布至今也已经好几年过去，如今 Java 也已经向 11 迈去，但是 Java 8 作出的改变可以说是革命性的，影响足够深远，学习 Java 8 应该是 Java 开发者的必修课。 今天给大家带来 Java 8 Stream 讲解，为什么直接讲这个，是因为只要你学完，立刻就能上手，并能让">
<meta name="keywords" content="java,stream,转载">
<meta property="og:type" content="article">
<meta property="og:title" content="【转】简洁又快速地处理集合——java8 Stream（上）">
<meta property="og:url" content="https://github.com/lgsxiaosen/post/26c1d83f.html">
<meta property="og:site_name" content="Learning Notes">
<meta property="og:description" content="作者：Howie_Y   主页：www.jianshu.com/u/79638e5f0743  Java 8 发布至今也已经好几年过去，如今 Java 也已经向 11 迈去，但是 Java 8 作出的改变可以说是革命性的，影响足够深远，学习 Java 8 应该是 Java 开发者的必修课。 今天给大家带来 Java 8 Stream 讲解，为什么直接讲这个，是因为只要你学完，立刻就能上手，并能让">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E6%B5%811.png">
<meta property="og:image" content="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E6%B5%812.png">
<meta property="og:updated_time" content="2019-01-19T08:29:23.061Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【转】简洁又快速地处理集合——java8 Stream（上）">
<meta name="twitter:description" content="作者：Howie_Y   主页：www.jianshu.com/u/79638e5f0743  Java 8 发布至今也已经好几年过去，如今 Java 也已经向 11 迈去，但是 Java 8 作出的改变可以说是革命性的，影响足够深远，学习 Java 8 应该是 Java 开发者的必修课。 今天给大家带来 Java 8 Stream 讲解，为什么直接讲这个，是因为只要你学完，立刻就能上手，并能让">
<meta name="twitter:image" content="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E6%B5%811.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/myblog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://github.com/lgsxiaosen/post/26c1d83f.html">





<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://lgsdaredevil.github.io/myblog"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>
  <title>【转】简洁又快速地处理集合——java8 Stream（上） | Learning Notes</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Learning Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblog/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      
        
        <li class="menu-item menu-item-comments">
          <a href="/myblog/comments" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            留言板
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://github.com/lgsxiaosen/myblog/post/26c1d83f.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="小森">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblog/images/android-chrome-192x192.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Learning Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【转】简洁又快速地处理集合——java8 Stream（上）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-19T10:06:50+08:00">
                2018-08-19
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/技术文章/" itemprop="url" rel="index">
                    <span itemprop="name">技术文章</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o">本文总阅读量</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>作者：Howie_Y</p>
</blockquote>
<blockquote>
<p>主页：<a href="http://www.jianshu.com/u/79638e5f0743" target="_blank" rel="noopener">www.jianshu.com/u/79638e5f0743</a></p>
</blockquote>
<p>Java 8 发布至今也已经好几年过去，如今 Java 也已经向 11 迈去，但是 Java 8 作出的改变可以说是革命性的，影响足够深远，学习 Java 8 应该是 Java 开发者的必修课。</p>
<p>今天给大家带来 Java 8 Stream 讲解，为什么直接讲这个，是因为只要你学完，立刻就能上手，并能让它在你的代码中大展身手。</p>
<p><strong>值得注意的是：学习 Stream 之前必须先学习 lambda 的相关知识。本文也假设读者已经掌握 lambda 的相关知识。</strong> </p>
<p><strong>本篇文章主要内容：</strong></p>
<ul>
<li>介绍 Stream 以及 Stream 是如何处理集合的</li>
<li>介绍 Stream 与集合的关系与区别</li>
<li>Stream 的基本方法介绍</li>
</ul>
<p><strong>一. 什么是 Stream</strong></p>
<p>Stream 中文称为 “流”，通过将集合转换为这么一种叫做 “流” 的元素序列，通过声明性方式，能够对集合中的每个元素进行一系列并行或串行的流水线操作。</p>
<p> 换句话说，你只需要告诉流你的要求，流便会在背后自行根据要求对元素进行处理，而你只需要 “坐享其成”。</p>
<p><strong>二. 流操作</strong></p>
<p><img src="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E6%B5%811.png" alt=""></p>
<p>整个流操作就是一条流水线，将元素放在流水线上一个个地进行处理。</p>
<p>其中数据源便是原始集合，然后将如 List的集合转换为 Stream类型的流，并对流进行一系列的中间操作，比如过滤保留部分元素、对元素进行排序、类型转换等；最后再进行一个终端操作，可以把 Stream 转换回集合类型，也可以直接对其中的各个元素进行处理，比如打印、比如计算总数、计算最大值等等</p>
<p>很重要的一点是，很多流操作本身就会返回一个流，所以多个操作可以直接连接起来，我们来看看一条 Stream 操作的代码：</p>
<p><img src="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E6%B5%812.png" alt=""></p>
<p>如果是以前，进行这么一系列操作，你需要做个迭代器或者 foreach 循环，然后遍历，一步步地亲力亲为地去完成这些操作；但是如果使用流，你便可以直接声明式地下指令，流会帮你完成这些操作。</p>
<p>有没有想到什么类似的？是的，就像 SQL 语句一样， select username from user where id = 1，你只要说明：“我需要 id 是 1 （id = 1）的用户（user）的用户名（username ）”，那么就可以得到自己想要的数据，而不需要自己亲自去数据库里面循环遍历查找。</p>
<p><strong>三. 流与集合</strong></p>
<p><strong>什么时候计算</strong></p>
<p>Stream 和集合的其中一个差异在于什么时候进行计算。</p>
<p>一个集合，它会包含当前数据结构中所有的值，你可以随时增删，但是集合里面的元素毫无疑问地都是已经计算好了的。</p>
<p>流则是按需计算，按照使用者的需要计算数据，你可以想象我们通过搜索引擎进行搜索，搜索出来的条目并不是全部呈现出来的，而且先显示最符合的前 10 条或者前 20 条，只有在点击 “下一页” 的时候，才会再输出新的 10 条。</p>
<p>再比方在线观看电影和你硬盘里面的电影，也是差不多的道理。</p>
<p><strong>外部迭代和内部迭代</strong></p>
<p>Stream 和集合的另一个差异在于迭代。</p>
<p>我们可以把集合比作一个工厂的仓库，一开始工厂比较落后，要对货物作什么修改，只能工人亲自走进仓库对货物进行处理，有时候还要将处理后的货物放到一个新的仓库里面。在这个时期，我们需要亲自去做迭代，一个个地找到需要的货物，并进行处理，这叫做外部迭代。</p>
<p>后来工厂发展了起来，配备了流水线作业，只要根据需求设计出相应的流水线，然后工人只要把货物放到流水线上，就可以等着接收成果了，而且流水线还可以根据要求直接把货物输送到相应的仓库。</p>
<p>这就叫做内部迭代，流水线已经帮你把迭代给完成了，你只需要说要干什么就可以了（即设计出合理的流水线）。</p>
<p>Java 8 引入 Stream 很大程度是因为，流的内部迭代可以自动选择一种合适你硬件的数据表示和并行实现；而以往程序员自己进行 foreach 之类的时候，则需要自己去管理并行等问题。</p>
<p><strong>一次性的流</strong></p>
<p>流和迭代器类似，只能迭代一次。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream = list.stream().map(Person::getName).sorted().limit(<span class="number">10</span>);         </span><br><span class="line">List&lt;String&gt; newList = stream.collect(toList());</span><br><span class="line">List&lt;String&gt; newList2 = stream.collect(toList());</span><br></pre></td></tr></table></figure>
<p>上面代码中第三行会报错，因为第二行已经使用过这个流，这个流已经被消费掉了</p>
<p><strong>四. 方法介绍，开始实战</strong></p>
<p>首先我们先创建一个 Person 泛型的 List</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Person&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">list.add(<span class="keyword">new</span> Person(<span class="string">"jack"</span>, <span class="number">20</span>));</span><br><span class="line">list.add(<span class="keyword">new</span> Person(<span class="string">"mike"</span>, <span class="number">25</span>));</span><br><span class="line">list.add(<span class="keyword">new</span> Person(<span class="string">"tom"</span>, <span class="number">30</span>));</span><br></pre></td></tr></table></figure>
<p>Person 类包含年龄和姓名两个成员变量 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> String name;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> age;</span><br></pre></td></tr></table></figure>
<p><strong>1. stream() / parallelStream()</strong></p>
<p>最常用到的方法，将集合转换为流</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List list = <span class="keyword">new</span> ArrayList();</span><br><span class="line"><span class="comment">// return Stream&lt;E&gt;</span></span><br><span class="line">list.stream();</span><br></pre></td></tr></table></figure>
<p>而 parallelStream() 是并行流方法，能够让数据集执行并行操作，后面会更详细地讲解</p>
<p><strong>2. filter(T -&gt; boolean)</strong></p>
<p>保留 boolean 为 true 的元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//保留年龄为 20 的 person 元素</span></span><br><span class="line">list = list.stream()</span><br><span class="line">           .filter(person -&gt; person.getAge() == <span class="number">20</span>)</span><br><span class="line">           .collect(toList());</span><br><span class="line"></span><br><span class="line"><span class="comment">//打印输出 [Person&#123;name='jack', age=20&#125;]</span></span><br></pre></td></tr></table></figure>
<p>collect(toList()) 可以把流转换为 List 类型，这个以后会讲解</p>
<p><strong>3. distinct()</strong></p>
<p>去除重复元素，这个方法是通过类的 equals 方法来判断两个元素是否相等的</p>
<p>如例子中的 Person 类，需要先定义好 equals 方法，不然类似[Person{name=’jack’, age=20}, Person{name=’jack’, age=20}] 这样的情况是不会处理的</p>
<p><strong>4. sorted() / sorted((T, T) -&gt; int)</strong></p>
<p>如果流中的元素的类实现了 Comparable 接口，即有自己的排序规则，那么可以直接调用 sorted() 方法对元素进行排序，如 Stream</p>
<p>反之, 需要调用 sorted((T, T) -&gt; int) 实现 Comparator 接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据年龄大小来比较：</span></span><br><span class="line">list = list.stream()</span><br><span class="line">          .sorted((p1, p2) -&gt; p1.getAge() - p2.getAge())</span><br><span class="line">          .collect(toList());</span><br></pre></td></tr></table></figure>
<p>当然这个可以简化为 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">list = list.stream()</span><br><span class="line">          .sorted(Comparator.comparingInt(Person::getAge))</span><br><span class="line">          .collect(toList());</span><br></pre></td></tr></table></figure>
<p><strong>5. limit(long n)</strong></p>
<p>返回前 n 个元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">list = list.stream()</span><br><span class="line">           .limit(<span class="number">2</span>)</span><br><span class="line">           .collect(toList());</span><br><span class="line"><span class="comment">//打印输出 [Person&#123;name='jack', age=20&#125;, Person&#123;name='mike', age=25&#125;]</span></span><br></pre></td></tr></table></figure>
<p><strong>6. skip(long n)</strong></p>
<p>去除前 n 个元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">list = list.stream()</span><br><span class="line">           .skip(<span class="number">2</span>)</span><br><span class="line">           .collect(toList());</span><br><span class="line"><span class="comment">//打印输出 [Person&#123;name='tom', age=30&#125;]</span></span><br></pre></td></tr></table></figure>
<p><strong>tips:</strong></p>
<ul>
<li>用在 limit(n) 前面时，先去除前 m 个元素再返回剩余元素的前 n 个元素</li>
<li>limit(n) 用在 skip(m) 前面时，先返回前 n 个元素再在剩余的 n 个元素中去除 m 个元素</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">list = list.stream()</span><br><span class="line">           .limit(<span class="number">2</span>)</span><br><span class="line">           .skip(<span class="number">1</span>)</span><br><span class="line">           .collect(toList());</span><br><span class="line"><span class="comment">//打印输出 [Person&#123;name='mike', age=25&#125;]</span></span><br></pre></td></tr></table></figure>
<p><strong>7. map(T -&gt; R)</strong></p>
<p>将流中的每一个元素 T 映射为 R（类似类型转换）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; newlist = </span><br><span class="line">list.stream().map(Person::getName).collect(toList());</span><br></pre></td></tr></table></figure>
<p>newlist 里面的元素为 list 中每一个 Person 对象的 name 变量</p>
<p><strong>8. flatMap(T -&gt; Stream**</strong>)**</p>
<p>将流中的每一个元素 T 映射为一个流，再把每一个流连接成为一个流</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">list.add(<span class="string">"aaa bbb ccc"</span>);</span><br><span class="line">list.add(<span class="string">"ddd eee fff"</span>);</span><br><span class="line">list.add(<span class="string">"ggg hhh iii"</span>);</span><br><span class="line"></span><br><span class="line">list = list.stream().map(s -&gt; s.split(<span class="string">" "</span>)).</span><br><span class="line">flatMap(Arrays::stream).collect(toList());</span><br></pre></td></tr></table></figure>
<p>上面例子中，我们的目的是把 List 中每个字符串元素以” “分割开，变成一个新的 List。</p>
<p>首先 map 方法分割每个字符串元素，但此时流的类型为 Stream，因为 split 方法返回的是 String[ ] 类型；所以我们需要使用 flatMap 方法，先使用Arrays::stream将每个 String[ ] 元素变成一个 Stream流，然后 flatMap 会将每一个流连接成为一个流，最终返回我们需要的 Stream</p>
<p><strong>9. anyMatch(T -&gt; boolean)</strong></p>
<p>流中是否有一个元素匹配给定的 T -&gt; boolean 条件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//是否存在一个 person 对象的 age 等于 20：</span></span><br><span class="line"><span class="keyword">boolean</span> b = list.stream().anyMatch(person -&gt; person.getAge() == <span class="number">20</span>);</span><br></pre></td></tr></table></figure>
<p><strong>10. allMatch(T -&gt; boolean)</strong></p>
<p>流中是否所有元素都匹配给定的 T -&gt; boolean 条件</p>
<p><strong>11. noneMatch(T -&gt; boolean)</strong></p>
<p>流中是否没有元素匹配给定的 T -&gt; boolean 条件</p>
<p><strong>12. findAny() 和 findFirst()</strong></p>
<ul>
<li>findAny()：找到其中一个元素 （使用 stream() 时找到的是第一个元素；使用 parallelStream() 并行时找到的是其中一个元素）</li>
<li>findFirst()：找到第一个元素</li>
</ul>
<p><em>值得注意的是，这两个方法返回的是一个 Optional**对象，它是一个容器类，能代表一个值存在或不存在，这个后面会讲到</em></p>
<p><strong>13. reduce((T, T) -&gt; T) 和 reduce(T, (T, T) -&gt; T)</strong></p>
<p>用于组合流中的元素，如求和，求积，求最大值等</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//计算年龄总和：</span></span><br><span class="line"><span class="keyword">int</span> sum = list.stream().map(Person::getAge).reduce(<span class="number">0</span>, (a, b) -&gt; a + b);</span><br><span class="line"><span class="comment">//与之相同:</span></span><br><span class="line"><span class="keyword">int</span> sum = list.stream().map(Person::getAge).reduce(<span class="number">0</span>, Integer::sum);</span><br></pre></td></tr></table></figure>
<p>其中，reduce 第一个参数 0 代表起始值为 0，lambda (a, b) -&gt; a + b 即将两值相加产生一个新值。</p>
<p>同样地：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//计算年龄总乘积：</span></span><br><span class="line"><span class="keyword">int</span> sum = list.stream().map(Person::getAge).reduce(<span class="number">1</span>, (a, b) -&gt; a * b);</span><br><span class="line"><span class="comment">//当然也可以</span></span><br><span class="line">Optional&lt;Integer&gt; sum = list.stream().map(Person::getAge).reduce(Integer::sum);</span><br></pre></td></tr></table></figure>
<p>即不接受任何起始值，但因为没有初始值，需要考虑结果可能不存在的情况，因此返回的是 Optional 类型。 </p>
<p><strong>13. count()</strong></p>
<p>返回流中元素个数，结果为 long 类型</p>
<p><strong>14. collect()</strong></p>
<p>收集方法，我们很常用的是 collect(toList())，当然还有 collect(toSet()) 等，参数是一个收集器接口，这个后面会另外讲。</p>
<p><strong>15. forEach()</strong></p>
<p>返回结果为 void，很明显我们可以通过它来干什么了，比方说：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//### 16. unordered()还有这个比较不起眼的方法，</span></span><br><span class="line"><span class="comment">//#返回一个等效的无序流，当然如果流本身就是无序的话，那可能就会直接返回其本身</span></span><br><span class="line"><span class="comment">//打印各个元素：</span></span><br><span class="line">list.stream().forEach(System.out::println);</span><br></pre></td></tr></table></figure>
<p>再比如说 MyBatis 里面访问数据库的 mapper 方法： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//向数据库插入新元素：</span></span><br><span class="line">list.stream().forEach(PersonMapper::insertPerson);</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://raw.githubusercontent.com/lgsdaredevil/newblog/master/css/images/wechatlike.jpg" alt="小森 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://raw.githubusercontent.com/lgsdaredevil/newblog/master/css/images/alipay.png" alt="小森 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/myblog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/myblog/tags/stream/" rel="tag"><i class="fa fa-tag"></i> stream</a>
          
            <a href="/myblog/tags/转载/" rel="tag"><i class="fa fa-tag"></i> 转载</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/myblog/post/b8d91ecc.html" rel="next" title="java虚拟机笔记（三）">
                <i class="fa fa-chevron-left"></i> java虚拟机笔记（三）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/myblog/post/9e7dbf5a.html" rel="prev" title="【转】简洁又快速地处理集合——java8 Stream（下）">
                【转】简洁又快速地处理集合——java8 Stream（下） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/myblog/images/android-chrome-192x192.png" alt="小森">
            
              <p class="site-author-name" itemprop="name">小森</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/myblog/archives/">
              
                  <span class="site-state-item-count">41</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblog/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblog/tags/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/lgsxiaosen/myblog" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小森</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




<!-- <div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div> -->

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  









  



  
  
    <script type="text/javascript" src="/myblog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script id="ribbon" type="text/javascript" size="300" alpha="0.6" zindex="-1" src="/myblog/lib/canvas-ribbon/canvas-ribbon.js"></script>
  


  


  <script type="text/javascript" src="/myblog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/myblog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/myblog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/myblog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/myblog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <script src="https://www.wenjunjiang.win/js/gitment.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: window.location.pathname, 
            owner: 'lgsxiaosen',
            repo: 'myblog',
            
            oauth: {
            
            
                client_secret: '876f37e17b73ba2870db494ed0b23e3194068dc9',
            
                client_id: '63acdc65d11c172104c4'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/myblog/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/myblog/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":80,"height":200},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
